package com.njit.WeStudy.config;

import com.njit.WeStudy.dataobject.User;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * yuruiqiao
 * 拦截器类
 * 2020-01-18
 * */
@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            NeedLogin needLogin = handlerMethod.getMethodAnnotation(NeedLogin.class);
            if(needLogin!=null){
                User user = (User) request.getSession().getAttribute("user");
                if(user==null){
                    response.sendRedirect("/login");
                    return false;
                }
            }
        }
        return true;
    }
}
